import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;

public class SearchServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String query = request.getParameter("query");
        if (query != null && !query.trim().isEmpty()) {
            // 处理搜索逻辑，例如查询数据库
            List<String> results = searchDatabase(query);

            // 将搜索结果存储在request属性中，以便在JSP页面中显示
            request.setAttribute("searchResults", results);

            // 转发请求到显示搜索结果的JSP页面
            RequestDispatcher dispatcher = request.getRequestDispatcher("searchResults.jsp");
            dispatcher.forward(request, response);
        } else {
            // 如果查询为空，重定向回搜索页面或显示错误消息
            response.sendRedirect("search.jsp"); // 假设有一个search.jsp页面
        }
    }

    private List<String> searchDatabase(String query) {
        // 这里应该是数据库查询逻辑，返回匹配的结果列表
        List<String> results = new ArrayList<>();
        // 数据库连接字符串，根据实际情况修改
        String url = "jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC&user=root&password=123456";
        String driver = "com.mysql.cj.jdbc.Driver";

        try {
            // 加载JDBC驱动
            Class.forName(driver);
            // 创建数据库连接
            try (Connection connection = DriverManager.getConnection(url)) {
                // 准备SQL语句
                String sql = "SELECT goods_name FROM goods WHERE goods_name LIKE ?";
                try (PreparedStatement statement = connection.prepareStatement(sql)) {
                    // 设置参数
                    statement.setString(1, "%" + query + "%");
                    // 执行查询
                    ResultSet resultSet = statement.executeQuery();
                    // 处理查询结果
                    while (resultSet.next()) {
                        results.add(resultSet.getString("goods_name"));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常，例如记录日志或返回错误消息
        }
        return results;
    }
}